package com.keter.common.exp;

import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.agent.model.Check;
import com.keter.framework.core.config.AvoidScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Iterator;
import java.util.Map;

/**
 * 调用Consul API执行操作
 */
@RestController
@AvoidScan
public class ConsulAPIExpController {
    private static Logger log = LoggerFactory.getLogger(ConsulAPIExpController.class);

    @Autowired
    private ConsulClient consulClient;
 
    /**
     * 剔除所有无效的服务实例
     * 发现不正常实例：
     * http://192.168.1.111:8500/v1/health/state/critical
     */
    @RequestMapping(value = "/services/clean", method = RequestMethod.GET)
    public void cheakCleanService() {
        log.info("***********************consul上无效服务清理开始*******************************************");
        //获取所有的services检查信息
        Iterator<Map.Entry<String, Check>> it = consulClient.getAgentChecks().getValue().entrySet().iterator();
        Map.Entry<String, Check> serviceMap;
        while (it.hasNext()) {
            //迭代数据
            serviceMap = it.next();
            //获取服务名称
            String serviceName = serviceMap.getValue().getServiceName();
            //获取服务ID
            String serviceId = serviceMap.getValue().getServiceId();
            log.info("服务名称 :{}**服务ID:{}", serviceName, serviceId);
            //获取健康状态值  PASSING：正常  WARNING  CRITICAL  UNKNOWN：不正常
            log.info("服务 :{}的健康状态值：{}", serviceName, serviceMap.getValue().getStatus());
            if ( serviceMap.getValue().getStatus() == Check.CheckStatus.CRITICAL) {
                log.info("服务 :{}为无效服务，准备清理...................", serviceName);
                consulClient.agentServiceDeregister(serviceId);
            }
        }
    }
}